package com.boot.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.boot.entity.Order;
import com.boot.entity.User;
import com.boot.mapper.UserDao;
import com.boot.service.OrderService;
import com.boot.util.AdResult;
import com.boot.util.GenerateUniqueId;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
public class PayController {
	
	@Resource
	private OrderService orderService;
	@Resource
	private UserDao userDao;
	
	//支付宝网关
	private static final String URL="https://openapi.alipay.com/gateway.do";
	//应用id
	private static final String APP_ID="2018040802519356";
	//私钥
	private static final String APP_PRIVATE_KEY="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDDJ7JWNj/MUZhCojKEld1UIm1YasWJy6ZghXUN4OfJq9yIe2K5agkQt8xNkZX0AirVeFdtEp5zyaKYythD1cjGu7wSySDMNODNTEIvbS5pNTFWm/j1hqMpLotoqzK+RpulH09K1qeggTVm9PwkCXFwmAM6tbsT5ExDmBOtirZTJkTYudo8y7fJZtYoKZJHiVo9d+fs1VmFpqCwS1zet261b8BW8vh7Rsc8m1cyhjX6JqvkDZLZ6+bG9wTidjVA4upjLLmmDMfTzTGxZadSdR3zsmLeyX7deyYEKosOFhGtT6CFkHsaIrErBeap5n7SYLXbNIjVmb5cQo9l/M/2iOnZAgMBAAECggEALT0Ogh2hPGPNv+SJg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1Y49O1Fbac5RkY3j2httCEOyKg/21fwjsuGcGooEWCZXLBaaL2qZJRPMp4A1MeW4ETJfE7GDR6U9KF1ebkeAqYb09RJ64eDcNy1EE5JYDP1FbM1d7rdyJ+H8CxpPT9Vu6f0JmnNWw==";
	//公钥
	private static final String ALIPAY_PUBLIC_KEY="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwyeyVjY/zFGYQqIyhJXdVCJtWGrFicumYIV1DeDnyavciHtiuWoJELfMTZGV9AIq1XhXbRKec8mimMrYQ9XIxru8EskgzDTgzUxCL20uaTUxVpv49YajKS6LaKsyvkabpR9PStanoIE1ZvT8JAlxcJgDOrW7E+RMQ5gTrYq2UyZE2LnaPMu3yWbWKCmSR4laPXfn7NVZhaagsEtc3rdutW/AVvL4e0bHPJtXMoY1+iar5A2S2evmxvcE4nY1QOLqYyy5pgzH080xsWWnUnUd87Ji3sl+3XsmBCqLDhYRrU+ghZB7GiKxKwXmqeZ+0mC12zSI1Zm+XEKPZfzP9ojp2QIDAQAB";
	//编码格式
	private static final String CHARSET="utf-8";
	//签名格式
	private static final String SIGN_TYPE="RSA2";
	
	//支付请求
	@RequestMapping("/pay/doPayByAliPay.do")
	@ResponseBody
	public AdResult payByAlipay(String user_id,String total_amount){
		AdResult adResult=new AdResult();
		//实例化客户端
		AlipayClient alipayClient = new DefaultAlipayClient(URL, APP_ID, APP_PRIVATE_KEY, "json", CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
		//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
		AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
		//SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
		AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
		String outTradeNo=GenerateUniqueId.generateOrder(user_id);
		model.setBody("用户向小广告账号充值");
		model.setSubject("充值");
		model.setOutTradeNo(outTradeNo);
		model.setTimeoutExpress("30m");
		model.setTotalAmount(total_amount);
		model.setProductCode("QUICK_MSECURITY_PAY");
		model.setSellerId("2088031845863554");//小广告实际支付宝收款账户的id
		//model.setSellerId("2088102175096755");//沙箱环境支付宝收款账户的id
		//保存支付订单
		Order order=new Order();
		order.setApp_id(APP_ID);
		order.setCreated_time(new Date());
		order.setIs_finished("0");
		order.setOut_trade_no(outTradeNo);
		order.setSeller_id("2088031845863554");
		order.setTotal_amount(new BigDecimal(total_amount));
		order.setUser_id(user_id);
		System.out.println(order);
		orderService.saveOrder(order);
		
		request.setBizModel(model);
		request.setNotifyUrl("http://47.94.166.156:80/adlet/xgg/handleResult.do");
		try {
	        //这里和普通的接口调用不同，使用的是sdkExecute
	        AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
	        adResult.setData(response.getBody());
	        adResult.setMsg(response.getCode());
	        System.out.println(response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。
		} catch (AlipayApiException e) {
		    e.printStackTrace();
		}
		adResult.setStatus(1);
		return adResult;
	}
	
	//异步响应请求
	@RequestMapping(value="/xgg/handleResult.do",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String checkAsynPost(HttpServletRequest request){
		AdResult adResult=new AdResult();
		//获取支付宝POST过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
		    String name = (String) iter.next();
		    String[] values = (String[]) requestParams.get(name);
		    String valueStr = "";
		    for (int i = 0; i < values.length; i++) {
		        valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
		  	}
		    //乱码解决，这段代码在出现乱码时使用。
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		
		System.out.println(params);
		
		//切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
		//boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
		try {
			boolean flag = AlipaySignature.rsaCheckV1(params,ALIPAY_PUBLIC_KEY,CHARSET,SIGN_TYPE);
			if(flag){
				//验签成功
				System.out.println("验签成功");
				//进行1、2、3、4步校验
				Order order=orderService.findOrder(params.get("out_trade_no"));
				if(order!=null){
					if(order.getSeller_id().equals(params.get("seller_id")) 
							&& order.getTotal_amount().equals(new BigDecimal(params.get("total_amount"))) 
							&& order.getApp_id().equals(APP_ID)){
						//到此校验完成
						if(params.get("trade_status")!=null && (params.get("trade_status").equals("TRADE_SUCCESS") || params.get("trade_status").equals("TRADE_FINISHED"))){
							System.out.println("success");
							//设置完成交易状态
							orderService.finishOrder(order.getOut_trade_no());
							//修改用户账号余额
							User user=new User();
							user.setUser_id(order.getUser_id());
							user.setBalance(order.getTotal_amount());
							userDao.rechargeUserBalance(user);
							return "success";
						}else{
							System.out.println("failure");
							return "failure";
						}
					}
				}else{
					return "failure";
				}
			}else{
				//验证失败 什么都不做
				System.out.println("验签失败，到此为止");
				return "failure";
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		return "failure";
	}
	
	
	
	@RequestMapping("/pay/drawCashByAliPay.do")
	@ResponseBody
	public AdResult authToken(String user_id,String total_amount,String payee_account,String status){
		AdResult adResult=new AdResult();
		System.out.println(total_amount+":"+payee_account);
		//实例化客户端
		AlipayClient alipayClient = new DefaultAlipayClient(URL, APP_ID, APP_PRIVATE_KEY, "json", CHARSET, ALIPAY_PUBLIC_KEY, "RSA2");
		AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
		String out_biz_no="drawcash"+GenerateUniqueId.generateOrder(user_id);
		request.setBizContent("{" +
		"    \"out_biz_no\":\""+out_biz_no+"\"," +
		"    \"payee_type\":\"ALIPAY_LOGONID\"," +
		"    \"payee_account\":\""+payee_account+"\"," +
		"    \"amount\":\""+total_amount+"\"" +
		"  }");
		try {
			AlipayFundTransToaccountTransferResponse response = alipayClient.execute(request);
			if(response.isSuccess()){
				System.out.println("调用成功"+response.getBody());
				adResult.setData(response.getBody());
				adResult.setMsg("提现成功");
				adResult.setStatus(1);
				if(response.getCode().equals("10000")){
					//接口调用成功
					User user=new User();
					user.setUser_id(user_id);
					user.setBalance(new BigDecimal("-"+total_amount));
					userDao.rechargeUserBalance(user);
					if(status.equals("0")){
						user.setAlipay(payee_account);
						userDao.saveUserAliPay(user);
					}
				}
			} else {
				System.out.println("调用失败"+response.getBody());
				adResult.setMsg("提现失败");
				adResult.setStatus(0);
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		return adResult;
	}
	
	
}
